﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Mozlite.WebUI.Mvc4
{
    /// <summary>
    /// 扩展方法类。
    /// </summary>
    public static class MvcExtension
    {
        /// <summary>
        /// 判断当前控制器上下文是否为区域上下文。
        /// </summary>
        /// <param name="context">控制器上下文。</param>
        /// <returns>返回结果。</returns>
        public static bool IsArea(this ControllerContext context)
        {
            return context.RouteData.DataTokens.ContainsKey("area");
        }

        /// <summary>
        /// 获取区域名称。
        /// </summary>
        /// <param name="context">控制器上下文。</param>
        /// <returns>返回结果。</returns>
        public static string GetAreaName(this ControllerContext context)
        {
            return context.RouteData.DataTokens["area"] as string;
        }

        /// <summary>
        /// 获取路由相关信息。
        /// </summary>
        /// <typeparam name="T">返回路由值类型。</typeparam>
        /// <param name="data">路由实例对象。</param>
        /// <param name="key">路由键值。</param>
        /// <param name="defaultValue">默认值。</param>
        /// <returns>返回路由信息值。</returns>
        public static T Get<T>(this RouteData data, string key, T defaultValue = default(T))
        {
            object ov;
            if (data.Values.TryGetValue(key, out ov))
                return ov.To<T>(defaultValue);
            return defaultValue;
        }

        /// <summary>
        /// 实体类型赋值。
        /// </summary>
        /// <typeparam name="T">实体类型。</typeparam>
        /// <param name="request">请求实例。</param>
        /// <returns>返回实例对象。</returns>
        public static T As<T>(this HttpRequestBase request) where T : class, new()
        {
            T value = new T();
            Type type = typeof(T);
            foreach (PropertyInfo p in type.GetProperties(BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.SetProperty))
            {
                try
                {
                    p.SetValue(value, request[p.Name].ChangeType(p.PropertyType), null);
                }
                catch
                {
                }
            }
            return value;
        }

        /// <summary>
        /// 实体类型赋值。
        /// </summary>
        /// <typeparam name="T">实体类型。</typeparam>
        /// <param name="request">请求实例。</param>
        /// <param name="name">名称。</param>
        /// <param name="defaultValue">默认值。</param>
        /// <returns>返回实例对象。</returns>
        public static T Get<T>(this HttpRequestBase request, string name, T defaultValue = default(T))
        {
            return request[name].To<T>(defaultValue);
        }
    }
}
